package com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.scItem;

import com.alibaba.citrus.cr.common.annotation.FunctionInvoker;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractDataSourceEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.ContractStatDimensionEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.cr.sales.plan.model.enums.StatPoolTypeEnum;
import com.alibaba.citrus.cr.sales.plan.repository.request.PageQueryPlanScItemExtendRepoRequest;
import com.alibaba.citrus.cr.sales.plan.repository.request.StatScItemQueryRequest;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanScItemExtendSDO;
import com.alibaba.citrus.cr.sales.plan.sdo.SalesPlanStatScItemSDO;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.MonthContractAndRollingCountResponse;
import com.alibaba.citrus.cr.sales.plan.dto.api.request.QueryContractByCustomerDimensionRequest;
import com.alibaba.citrus.cr.sales.plan.facade.service.SalesPlanCommonService;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.SalesPlanStatAtomAbstract;
import com.alibaba.citrus.cr.sales.plan.facade.service.statistics.stat.model.SalesPlanStatRequest;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.PlanScItemStatBySalesDepartmentCountRequest;
import com.epoch.app.bcorder.sales_plan.salesplandetail.dto.PlanScItemStatBySalesDepartmentCountResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author luyi
 * @date 2021/12/2 8:30 下午
 */
public class ScItemDepartmentStatService extends SalesPlanStatAtomAbstract {

    private static final Log log = Log.getLogger(ScItemDepartmentStatService.class);

    public ScItemDepartmentStatService(SalesPlanStatRequest statRequest,CountDownLatch latch){
        super.statRequest = statRequest;
        super.latch = latch;
    }

    @Override
    protected void handle(SalesPlanStatRequest statRequest) {
        statDepartmentScItem(statRequest.getSalesPlan(),statRequest.getYear(),statRequest.getMonth(),statRequest.getIsUpdateExtend());
    }

    @Override
    protected String taskName() {
        return "statDepartmentScItem";
    }

    /**
     * 货品维度
     * 销售部门货品汇总
     *
     * @param salesPlan
     */
    @FunctionInvoker(printLog = true)
    private void statDepartmentScItem(SalesPlanSDO salesPlan, String year, String month, Boolean isUpdateExtend) {
        PlanScItemStatBySalesDepartmentCountRequest request = new PlanScItemStatBySalesDepartmentCountRequest();
        request.setPlanId(salesPlan.getId());
        PlanScItemStatBySalesDepartmentCountResponse planScItemStatBySalesDepartmentCount = salesPlanDetailService.planScItemStatBySalesDepartmentCount(request);
        if (Objects.isNull(planScItemStatBySalesDepartmentCount)) {
            log.info("SalesPlanStatServiceImpl_scItemStat_statCount_is_null,statDepartmentScItem");
            return;
        }
        Integer count = planScItemStatBySalesDepartmentCount.getCount();
        if (count == null || count <= 0) {
            log.info("SalesPlanStatServiceImpl_scItemStat_statCount_is_null,statDepartmentScItem2");
            return;
        }
        int totalPage = (count + CUSTOMER_ADDRESS_PAGE_SIZE - 1) / CUSTOMER_ADDRESS_PAGE_SIZE;
        log.info("SalesPlanStatServiceImpl_statDepartmentScItem_statCount_size={},totalPage={}",count,totalPage);
        List<SalesPlanScItemExtendSDO> batchCreatePlanScItemExtendList = new ArrayList();
        for (int i = 1; i <= totalPage; i++) {
            StatScItemQueryRequest statQueryRequest = new StatScItemQueryRequest();
            statQueryRequest.setPlanId(salesPlan.getId());
            statQueryRequest.setOrgSalesDepartment(true);
            statQueryRequest.setSize(CUSTOMER_ADDRESS_PAGE_SIZE);
            statQueryRequest.setPage(i);
            List<SalesPlanStatScItemSDO> salesPlanStatScItemList = salesPlanLineRepository.queryStatPlanScItemList(statQueryRequest);
            if (CollectionUtils.isEmpty(salesPlanStatScItemList)) {
                log.info("SalesPlanStatServiceImpl_scItemStat_queryStatList_is_null,statDepartmentScItem");
                return;
            }
            log.info("SalesPlanStatServiceImpl_statDepartmentScItem_queryStatList_size={}",salesPlanStatScItemList.size());
            //批量查询销售部门货品合同量，合同金额
            Set<String> departmentList = new HashSet<>();
            Set<String> scItemIdList = new HashSet<>();
            for (SalesPlanStatScItemSDO salesPlanStatScItem : salesPlanStatScItemList) {
                if (StringUtils.isNotBlank(salesPlanStatScItem.getBizId())) {
                    departmentList.add(salesPlanStatScItem.getBizId());
                }
                scItemIdList.add(salesPlanStatScItem.getScItemId());
            }

            Map<String, com.epoch.app.bcorder.model.dto.OrganizationSDO> bizOrgMap = salesPlanOutCommonService.getOrganizationMapByIds(departmentList,false);

            QueryContractByCustomerDimensionRequest queryContractRequest = new QueryContractByCustomerDimensionRequest();
            queryContractRequest.setType(ContractStatDimensionEnum.DEPARTMENT_SC_ITEM.getCode());
            queryContractRequest.setContractYear(year);
            queryContractRequest.setPlanMonth(month);
            queryContractRequest.setOrgSalesDepartmentCodes(Lists.newArrayList(departmentList));
            queryContractRequest.setScItemIds(Lists.newArrayList(scItemIdList));
            queryContractRequest.setDataSource(ContractDataSourceEnum.CUSTOMER.getCode());
            List<MonthContractAndRollingCountResponse> monthContractList = contractRepository.queryQuantityListByAddressAndScItem(queryContractRequest);
            Map<String, MonthContractAndRollingCountResponse> collect = Maps.newHashMap();
            if (CollectionUtils.isNotEmpty(monthContractList)) {
                collect = monthContractList.stream().collect(Collectors.toMap(m -> SalesPlanCommonService.getCombinationKey(m.getOrgSalesDepartmentCode(), m.getScItemId()), m -> m));
            }
            for (SalesPlanStatScItemSDO planStatScItem : salesPlanStatScItemList) {
                planStatScItem.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
                planStatScItem.setBizType(SalesStatBizTypeEnum.SALES_DEPARTMENT.getBizType());
                //需要查合同量补充
                MonthContractAndRollingCountResponse monthContract = collect.get(SalesPlanCommonService.getCombinationKey(planStatScItem.getBizId(), planStatScItem.getScItemId()));
                setStatContractInfo(planStatScItem, monthContract);
                calculateSatisfaction(salesPlan.getStatus(), planStatScItem);

                //20220901  汇总计算单价，，折前计划金额/计划量，两位精度
                BigDecimal costInsuranceFreight = planStatScItem.getMonthCount()==0?new BigDecimal(0):new BigDecimal(planStatScItem.getBeforeMonthMoney()).divide(new BigDecimal(planStatScItem.getMonthCount()),0,BigDecimal.ROUND_HALF_UP);
                planStatScItem.setCostInsuranceFreight(costInsuranceFreight.longValue());
                // 汇总 计算出库价，，折前出库金额/计划量，两位精度
                BigDecimal outboundPrice = planStatScItem.getMonthCount()==0?new BigDecimal(0):new BigDecimal(planStatScItem.getPlanOutboundMoney()).divide(new BigDecimal(planStatScItem.getMonthCount()),0,BigDecimal.ROUND_HALF_UP);
                planStatScItem.setOutboundPrice(outboundPrice.longValue());

                com.epoch.app.bcorder.model.dto.OrganizationSDO org = bizOrgMap.get(planStatScItem.getBizId());
                planStatScItem.setBizOutId(org.getCode());
            }
            Boolean result = salesPlanScItemStatRepository.batchCreatePlanScItem(salesPlanStatScItemList);
            log.info("SalesPlanStatServiceImpl_statcItem_batchCreatePlanScItem_result={},statDepartmentScItem",result);

            //同步extend表   调整发布时才会触发
            if(isUpdateExtend){
                PageQueryPlanScItemExtendRepoRequest extendRepoRequest = new PageQueryPlanScItemExtendRepoRequest();
                extendRepoRequest.setPlanId(String.valueOf(salesPlan.getId()));
                extendRepoRequest.setModel(1);
                extendRepoRequest.setPoolType(StatPoolTypeEnum.SC_ITEM.getPoolType());
                extendRepoRequest.setBizType(SalesStatBizTypeEnum.SALES_DEPARTMENT.getBizType());
                extendRepoRequest.setBizId(Lists.newArrayList(departmentList));
                extendRepoRequest.setScItemIdList(Lists.newArrayList(scItemIdList));
                extendRepoRequest.setStart(0);
                extendRepoRequest.setSize(1000);
                PageResult<List<SalesPlanScItemExtendSDO>> extendResult = salesPlanScItemExtendRepository.pageQueryPlanScItemExtendList(extendRepoRequest);
                log.info("SalesPlanStatServiceImpl_statcItem_updateExtend_pageQueryPlanScItemExtendList_request={},result={},statDepartmentScItem",JSONObject.toJSON(extendRepoRequest),JSONObject.toJSON(extendResult));
                List<SalesPlanScItemExtendSDO> extendSDOList = extendResult.getContent();
                Map<String, SalesPlanScItemExtendSDO> extendSDOMap = Maps.newHashMap();
                if (CollectionUtils.isNotEmpty(extendSDOList)) {
                    extendSDOMap = extendSDOList.stream().collect(Collectors.toMap(m -> SalesPlanCommonService.getCombinationKey(m.getBizId(), m.getScItemId()), m -> m));
                }

                for (SalesPlanStatScItemSDO planStatScItem : salesPlanStatScItemList) {
                    SalesPlanScItemExtendSDO extendSDO = extendSDOMap.get(SalesPlanCommonService.getCombinationKey(planStatScItem.getBizId(), planStatScItem.getScItemId()));
                    if(extendSDO == null){
                        extendSDO = new SalesPlanScItemExtendSDO();
                        BeanUtils.copyProperties(planStatScItem, extendSDO);
                        extendSDO.setModel(1);
                        extendSDO.setModelId(String.valueOf(planStatScItem.getPlanId()));
                        batchCreatePlanScItemExtendList.add(extendSDO);
                        continue;
                    }
                    if(!planStatScItem.getTaskCount().equals(extendSDO.getTaskCount())){
                        extendSDO.setTaskCount(planStatScItem.getTaskCount());
                        extendSDO.setTaskOutboundMoney(planStatScItem.getTaskOutboundMoney());
                        extendSDO.setBeforeTaskMoney(planStatScItem.getBeforeTaskMoney());
                        extendSDO.setTaskMoney(planStatScItem.getTaskMoney());
                        extendSDO.setContractDifferenceCount(planStatScItem.getContractDifferenceCount());
                        extendSDO.setMonthFirstCount(planStatScItem.getMonthFirstCount());
                        extendSDO.setMonthMiddleCount(planStatScItem.getMonthMiddleCount());
                        extendSDO.setMonthLastCount(planStatScItem.getMonthLastCount());
                        extendSDO.setMonthFirstTaskCount(planStatScItem.getMonthFirstTaskCount());
                        extendSDO.setMonthMiddleTaskCount(planStatScItem.getMonthMiddleTaskCount());
                        extendSDO.setMonthLastTaskCount(planStatScItem.getMonthLastTaskCount());
                        extendSDO.setMonthFirstAdjustCount(planStatScItem.getMonthFirstAdjustCount());
                        extendSDO.setMonthFirstAdjustTotalCount(planStatScItem.getMonthFirstAdjustTotalCount());
                        extendSDO.setMonthMiddleAdjustCount(planStatScItem.getMonthMiddleAdjustCount());
                        extendSDO.setMonthMiddleAdjustTotalCount(planStatScItem.getMonthMiddleAdjustTotalCount());
                        extendSDO.setMonthLastAdjustCount(planStatScItem.getMonthLastAdjustCount());
                        extendSDO.setMonthLastAdjustTotalCount(planStatScItem.getMonthLastAdjustTotalCount());
                        Boolean b = salesPlanScItemExtendRepository.editSalesPlanScItemExtend(extendSDO);
                        log.info("SalesPlanStatServiceImpl_statcItem_updateExtend_extendSDO={},result={},statDepartmentScItem", JSONObject.toJSON(extendSDO),b);
                    }
                };
            }
        }

        if(CollectionUtils.isNotEmpty(batchCreatePlanScItemExtendList)){
            Boolean b = salesPlanScItemExtendRepository.batchCreatePlanScItemExtend(batchCreatePlanScItemExtendList);
            log.info("SalesPlanStatServiceImpl_statcItem_updateExtend_batchCreatePlanScItemExtend_request={},result={},statDepartmentScItem",JSONObject.toJSON(batchCreatePlanScItemExtendList),b);
        }
    }
}
